package com.cory.module.oplog.service;

import java.time.LocalDateTime;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import com.cory.module.oplog.domain.entity.Oplog;
import com.cory.module.oplog.domain.entity.OplogAttribute;
import com.cory.module.oplog.mapper.OplogAttributeMapper;
import com.cory.module.oplog.mapper.OplogMapper;
import com.cory.utils.lang.DateUtils;

/**
 *  服务实现类
 *
 * @author xc
 * @since 2022-01-10
 */
@Service
public class OplogService extends ServiceImpl<OplogMapper, Oplog> {
    @Autowired
    private OplogAttributeMapper oplogAttributeMapper;
    
    @Transactional(rollbackFor=Exception.class)
    public void saveLog(Oplog log, List<OplogAttribute> attributes) {
        this.save(log);
        attributes.forEach(i -> {
            i.setOplogId(log.getId());
            
            oplogAttributeMapper.insert(i);
        });
    }
    
    @Override
    public boolean save(Oplog log) {
        log.setLogTime(LocalDateTime.now());
        
        return super.save(log);
    }
    
    public List<Oplog> list(Oplog param) {
        QueryWrapper<Oplog> query = new QueryWrapper<>();
        query.orderByDesc("id");
        if (StringUtils.isNotBlank(param.getObjectAlias())) {
            query.eq("object_alias", param.getObjectAlias());
        }
        if (param.getObjectId() != null) {
            query.eq("object_id", param.getObjectId());
        }
        if (StringUtils.isNotBlank(param.getStartDate())) {
            query.ge("log_time", DateUtils.parseDate(param.getStartDate()));
        }
        if (StringUtils.isNotBlank(param.getEndDate())) {
            query.le("log_time", DateUtils.parseDate(param.getEndDate() + " 23:59:59"));
        }
        return super.list(query);
    }
    
    public List<OplogAttribute> listAttributes(List<Long> logIds) {
        if (logIds == null || logIds.size() == 0) {
            return Lists.newArrayList();
        }
        
        QueryWrapper<OplogAttribute> query = new QueryWrapper<>();
        query.in("oplog_id", logIds);
        
        return oplogAttributeMapper.selectList(query);
    }
}
